(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:cityName
     * @description

     用法：
     <city-name ng-model="city_id" dft="1"></city-name>
     注：必须绑定ng-model;dft=1代表自动选中最后一个节点

     * # myarea
     */
    angular.module('webApp')
        .directive('cityName', function() {
            return {
                restrict: 'E',
                template: '<span ng-if="area_name">{{area_name}}</span>',
                // replace: true,
                require: 'ngModel',
                scope: {
                    ngModel: '=',
                },
                controller: ['$templateCache', '$scope', 'dataService', '$compile', '$timeout', function($templateCache, $scope, dataService, $compile, $timeout) {
                    $scope.ngModel = $scope.ngModel || [];

                    $scope.area_name = [];
                    $scope.initData = function() {
                        if ($scope.ngModel != 1) {
                            var a = [];
                            dataService.getAllCity(function(citys) {
                                for (var i in $scope.ngModel) {
                                    if (citys[$scope.ngModel[i]]) {
                                        a.push(citys[$scope.ngModel[i]]);
                                    }
                                    // else {
                                    //     a.push(i);
                                    // }
                                }
                                $scope.area_name = a;
                            });

                            // dataService.areaGetById($scope.ngModel).then(function(area) {
                            //     $scope.area_name = area;
                            // });
                        } else {
                            $scope.area_name = "全国";
                        }
                    }
                }],
                link: function(scope, element, attrs, ctrl) {
                    // scope.initData();

                    scope.$watch('ngModel', function(newValue, oldValue, scope) {
                        if (newValue) {
                            scope.initData();
                        }
                    });

                }
            }
        });
})();